﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PubNub_Messaging;

namespace testpubnub
{
    public partial class Form1 : Form
    {
        public const int length = 128;
        public double[] pricearray = new double[length];
        public void refresharray()
        {
            for(int i=length-1,j=0;i>=0;i--,j++)
            {
                if (dt.Rows.Count > j+1)
                {
                    pricearray[i] =double.Parse((string)dt.Rows[j][1]);

                }
                else
                    pricearray[i] = 0;
            }
        }
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            showme();
        }
        DataTable dt = new DataTable();
        public void showme()//绘制wav波形和对其的字符
        {

            Bitmap bwav = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            Graphics gph = Graphics.FromImage(bwav);
            gph.Clear(Color.Black);
            Pen pen1 = new Pen(Brushes.Gray);
            Point p1 = new Point(0, 0);
            Point p2 = new Point(0, 0);
            int width = pictureBox1.Width;
            int height = pictureBox1.Height;
            int grid = 20;
            pen1.Width = 1;
            for (int i = 0; i < width; i += grid)
            {
                p1 = new Point(i, 0);
                p2 = new Point(i, height);
                gph.DrawLine(pen1, p1, p2);
            }
            for (int i = 0; i < height; i += grid)
            {
                p1 = new Point(0, i);
                p2 = new Point(width, i);
                gph.DrawLine(pen1, p1, p2);
            }
            p1 = new Point(0, pictureBox1.Height/2);
            p2 = new Point(0, pictureBox1.Height/2);

            pen1.Width = 2;
            pen1.Color = Color.LightBlue;

            for (int i = 0; i < pricearray.Length; i += 1)
            {
                p1 = p2;
                int x = i * width / pricearray.Length;
                int y = (int)((pricearray[i]-(double.Parse(labelsell.Text.Replace("$",""))))*-10);
                p2 = new Point(x, y + pictureBox1.Height / 2);
                gph.DrawLine(pen1, p1, p2);

            }
            pictureBox1.Image = bwav;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            getticker();
            gettrade();
            getlag();
        //    listBox1.DrawItem+=new DrawItemEventHandler(listBox1_DrawItem);
            dt.Columns.Add("DateTime", typeof(System.DateTime));
            dt.Columns.Add("Price", typeof(System.String));
            dt.Columns.Add("Amount", typeof(System.String));
            dataGridView1.DataSource = dt;
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.MultiSelect = false;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //dataGridView1.
            dataGridView1.ReadOnly = true;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.ReadOnly = true;
            dataGridView1.AllowUserToResizeRows = false;
        }
        public void getticker()
        {
            string status = "";
            Pubnub pubnub = new Pubnub(
                   "demo",
                   "sub-c-50d56e1e-2fd9-11e3-a041-02ee2ddab7fe",
                   "",
                   false);
            string channel = "d5f06780-30a8-4a48-a2f8-7ed181b4a13f";

            pubnub.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
            {
                if (e.PropertyName == "ReturnMessage")
                {
                    Dictionary<string, object> _message = (Dictionary<string, object>)(((Pubnub)sender).ReturnMessage);

            //   MessageBox.Show("Received Message -> '" + _message.Values+ "'");
                  labelhigh.Text= ((Dictionary<string, object>)((Dictionary<string, object>)_message["ticker"])["high"])["display"].ToString();
                  labellow.Text = ((Dictionary<string, object>)((Dictionary<string, object>)_message["ticker"])["low"])["display"].ToString();
                  labelavg.Text = ((Dictionary<string, object>)((Dictionary<string, object>)_message["ticker"])["avg"])["display"].ToString();
                  labelvwap.Text = ((Dictionary<string, object>)((Dictionary<string, object>)_message["ticker"])["vwap"])["display"].ToString();
                  labelvol.Text = ((Dictionary<string, object>)((Dictionary<string, object>)_message["ticker"])["vol"])["display"].ToString();
                  labellast.Text = ((Dictionary<string, object>)((Dictionary<string, object>)_message["ticker"])["last"])["display"].ToString();
                  labelbuy.Text = ((Dictionary<string, object>)((Dictionary<string, object>)_message["ticker"])["buy"])["display"].ToString();
                  labelsell.Text = ((Dictionary<string, object>)((Dictionary<string, object>)_message["ticker"])["sell"])["display"].ToString();
                }
            };
            pubnub.subscribe(channel);

        }
        public void getlag()
        {
            string status = "";
            Pubnub pubnub = new Pubnub(
                   "demo",
                   "sub-c-50d56e1e-2fd9-11e3-a041-02ee2ddab7fe",
                   "",
                   false);
            string channel = "85174711-be64-4de1-b783-0628995d7914";

            pubnub.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
            {
                if (e.PropertyName == "ReturnMessage")
                {
                    Dictionary<string, object> _message = (Dictionary<string, object>)(((Pubnub)sender).ReturnMessage);

                    //   MessageBox.Show("Received Message -> '" + _message.Values+ "'");
                    double lag= double.Parse((((Dictionary<string, object>)_message["lag"])["age"]).ToString())/1000000;
                    toolStripStatusLabel2.Text= lag.ToString();
                }
            };
            pubnub.subscribe(channel);
        }
        //private void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
        //{   // Set the DrawMode property to draw fixed sized items.
        //    listBox1.DrawMode = DrawMode.OwnerDrawFixed;
        //    // Draw the background of the ListBox control for each item.
        //    e.DrawBackground();   // Define the default color of the brush as black.

        //    // Determine the color of the brush to draw each item based on the index of the item to draw.
        //    string s = this.listBox1.Items[e.Index].ToString();
        //    if (s.Contains("+"))
        //    {
        //        e.Graphics.DrawString(s, this.Font, Brushes.Red, e.Bounds);
        //    }
        //    else
        //    {
        //        e.Graphics.DrawString(s, this.Font, Brushes.Green, e.Bounds);
        //    }
        //}
        public void gettrade()
        {
            string status = "";
            Pubnub pubnub = new Pubnub(
                   "demo",
                   "sub-c-50d56e1e-2fd9-11e3-a041-02ee2ddab7fe",
                   "",
                   false);
            string channel = "dbf1dee9-4f2e-4a08-8cb7-748919a71b21";

            pubnub.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
            {
                if (e.PropertyName == "ReturnMessage")
                {
                    Dictionary<string, object> _message = (Dictionary<string, object>)(((Pubnub)sender).ReturnMessage);
                    if(((Dictionary<string, object>)_message["trade"])["price_currency"].ToString()=="USD")
                    {
                        
                   //     DateTime dt = new DateTime(long.Parse(((Dictionary<string, object>)_message["trade"])["tid"].ToString()));
                   //     listBox1.Items.Add(dt.ToShortTimeString());
                      double price=double.Parse( ((Dictionary<string, object>)_message["trade"])["price"].ToString());
                      double amount=double.Parse( ((Dictionary<string, object>)_message["trade"])["amount"].ToString());
                      long date = long.Parse(((Dictionary<string, object>)_message["trade"])["date"].ToString());
                      if (((Dictionary<string, object>)_message["trade"])["trade_type"].ToString() == "ask")
                      {
                          DataRow dr = dt.NewRow();
                          dr[0] = UnixTime.FromUnixTime(date);
                          dr[1] = String.Format("{0:0.0000}", price);
                          dr[2] = String.Format("{0:0.0000}", amount);
                          dt.Rows.InsertAt(dr,0);
                          dataGridView1.Rows[0].DefaultCellStyle.BackColor=Color.Black;
                          dataGridView1.Rows[0].DefaultCellStyle.ForeColor = Color.Red;
                          dataGridView1.Rows[0].DefaultCellStyle.Font = new Font("黑体", (float)7);
                          refresharray();
                          showme();
                      }
                      else
                      {
                          DataRow dr = dt.NewRow();
                          dr[0] = UnixTime.FromUnixTime(date);
                          dr[1] = String.Format("{0:0.0000}", price);
                          dr[2] = String.Format("{0:0.0000}", amount);
                          dt.Rows.InsertAt(dr, 0);
                          dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Black;
                          dataGridView1.Rows[0].DefaultCellStyle.ForeColor = Color.Green;
                          dataGridView1.Rows[0].DefaultCellStyle.Font = new Font("黑体", (float)7);
                          refresharray();
                          showme();
                      }
                    }

                }
            };
            pubnub.subscribe(channel);
        }
        

    }
}
